using Microsoft.EntityFrameworkCore;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Services
{
    public class CommentService : BaseService<Comment>, ICommentService
    {
        public CommentService(PandaSystemContext context) : base(context)
        {
        }

        public async Task<List<Comment>> GetCommentsByPostIdAsync(Guid postId)
        {
            return await _dbSet
                .Include(c => c.User)
                .Include(c => c.Likes)
                .Where(c => c.PostId == postId && c.ParentCommentId == null && c.IsDeleted != true)
                .OrderByDescending(c => c.CreatedAt)
                .ToListAsync();
        }

        public async Task<List<Comment>> GetCommentsByUserIdAsync(Guid userId)
        {
            return await _dbSet
                .Include(c => c.Post)
                .Include(c => c.Likes)
                .Where(c => c.UserId == userId && c.IsDeleted != true)
                .OrderByDescending(c => c.CreatedAt)
                .ToListAsync();
        }

        public async Task<List<Comment>> GetRepliesByCommentIdAsync(Guid commentId)
        {
            return await _dbSet
                .Include(c => c.User)
                .Include(c => c.Likes)
                .Where(c => c.ParentCommentId == commentId && c.IsDeleted != true)
                .OrderBy(c => c.CreatedAt)
                .ToListAsync();
        }

        public override async Task<Comment> CreateAsync(Comment comment)
        {
            comment.CommentId = Guid.NewGuid();
            comment.CreatedAt = DateTime.UtcNow;
            comment.IsDeleted = false;
            
            await _dbSet.AddAsync(comment);
            await _context.SaveChangesAsync();
            
            return comment;
        }

        public override async Task<bool> DeleteAsync(Guid id)
        {
            var comment = await _dbSet.FindAsync(id);
            if (comment == null)
                return false;

            // 软删除
            comment.IsDeleted = true;
            await _context.SaveChangesAsync();
            
            return true;
        }
    }
} 